package com.tjetc;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.Properties;

/**
 * @author: gaoyongxiang
 * @date: 2025/8/15
 * @version: v1.0
 */
@SuppressWarnings("all")
public class _2JdbcConnect {
    /*
        mysql连接的方法
        1. 最基础的链接方法
        2. 动态加载类（反射） 因为我们知道mysql中Driver的实现类地址
        3. 统一管理连接驱动 DriverManager 帮助我们注册驱动并获取连接
        4. 省略获取Driver驱动类 因为mysql会自动创建驱动类
        5. 使用配置文件将数据库账号和密码移出java类中
     */

    public static void main(String[] args) throws ClassNotFoundException, IOException, SQLException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        // 通过配置文件加载
        Properties properties = new Properties();
        properties.load(new FileInputStream("/Users/gaoyongxiang/百度网盘/IDEA-Java/202507-java-se/chapter21/src/main/resources/jdbc.properties"));
//        Class<?> aClass = Class.forName(properties.getProperty("jdbc.driver"));
//        Driver driver = (Driver) aClass.getConstructor().newInstance();
//        DriverManager.registerDriver(driver);
        /*
            JVM调用的  SPI机制 会拿到META-INF/services/java.sql.Driver文件

            public class Driver extends NonRegisteringDriver implements java.sql.Driver {
                public Driver() throws SQLException {
                }

                static {
                    try {
                        DriverManager.registerDriver(new Driver());
                    } catch (SQLException var1) {
                        throw new RuntimeException("Can't register driver!");
                    }
                }
            }

         */
        Connection connection = DriverManager.getConnection(
                properties.getProperty("jdbc.url"),
                properties.getProperty("jdbc.username"),
                properties.getProperty("jdbc.password"));
        System.out.println(connection);

        String sql = "insert into bank (name, money) values ('zhangsan', 500);";
        Statement statement = connection.createStatement();
        // 受影响行数
        int row = statement.executeUpdate(sql);
        System.out.println(row);
        statement.close();
        connection.close();

    }

}